# models all the user-configurable settings in the app
# there should only therefore need to be one row in this table
class Setting < ActiveRecord::Base
  validates(:webmaster_email, :presence => true)
  validates(:timezone, :presence => true)
  after_save(:copy_to_config)
  
  # loads the one and only row
  def self.get
    first || create(:webmaster_email => "webmaster@example.com", :timezone => "UTC")
  end
  
  # copies the stored settings to the configatron settings collection (singleton-like class method)
  def self.copy_to_config
    # get the latest settings and copy
    # do nothing on rescue to avoid weird app startup timing errors
    get.copy_to_config rescue nil
  end
  
  # copies the stored settings to the configatron settings collection
  def copy_to_config
    # get a copy of the settings attributes, minus the irrelevant ones
    hash = attributes.dup
    %w(id created_at updated_at).each{|k| hash.delete(k)}
    
    # send to configatron
    CONF.configure_from_hash(hash)
  end
end
